<!--  -->
<template>
    <div class="page-container">
        <div class="header-panel">
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
                <el-form-item label="用户名称" prop="userName">
                    <el-input v-model="queryParams.userName" placeholder="请输入用户名称" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item label="手机号码" prop="phonenumber">
                    <el-input v-model="queryParams.phonenumber" placeholder="请输入手机号码" clearable style="width: 240px" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                    <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
                        v-hasPermi="['system:user:add']">新增</el-button>

                    <el-button type="success" plain icon="el-icon-edit" :disabled="single" @click="handleUpdate"
                        v-hasPermi="['system:user:edit']">修改</el-button>

                    <el-button type="danger" plain icon="el-icon-delete" :disabled="multiple" @click="handleDelete"
                        v-hasPermi="['system:user:remove']">删除</el-button>

                </el-form-item>
            </el-form>
        </div>

        <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange" size="medium"
            height="calc(100% - 100px)">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="用户编号" align="center" key="userId" prop="userId" width="320" />
            <el-table-column label="用户名称" align="center" key="userName" prop="userName" :show-overflow-tooltip="true" />
            <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
            <!-- <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName"
                :show-overflow-tooltip="true" /> -->
            <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
            <el-table-column label="状态" align="center" prop="status">
                <template slot-scope="scope">
                    {{ scope.row.status == '0' ? '正常' : '停用' }}
                </template>
            </el-table-column>
            <el-table-column label="创建时间" align="center" prop="createTime" width="160">
            </el-table-column>
            <el-table-column label="操作" align="center" width="260" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:user:edit']">修改</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                        v-hasPermi="['system:user:remove']">删除</el-button>
                    <el-button size="mini" type="text" icon="el-icon-delete" @click="handleResetPwd(scope.row)"
                        v-hasPermi="['system:user:resetPwd']">重置密码</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination background style="text-align: center;margin-top: 10px;" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" :current-page="page.pageNum" :page-sizes="[50, 100, 200, 500]"
            :page-size="page.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="page.total">
        </el-pagination>



        <!-- 添加或修改用户配置对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" :close-on-click-modal="false" append-to-body
            @close="resetForm">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户昵称" prop="nickName">
                            <el-input v-model="form.nickName" placeholder="请输入用户昵称" maxlength="30" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="角色">
                            <el-select v-model="form.roleIds" multiple placeholder="请选择角色">
                                <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.roleName"
                                    :value="item.roleId" :disabled="item.status == 1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="手机号码" prop="phonenumber">
                            <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item v-if="form.userId == undefined" label="用户名称" prop="userName">
                            <el-input v-model="form.userName" placeholder="请输入用户名称" maxlength="30" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item v-if="form.userId == undefined" label="用户密码" prop="password">
                            <el-input v-model="form.password" placeholder="请输入用户密码" type="password" maxlength="20"
                                show-password />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="用户性别">
                            <el-select v-model="form.sex" placeholder="请选择性别">
                                <el-option v-for="dict in sexOptions" :key="dict.value" :label="dict.label"
                                    :value="dict.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态">
                            <el-radio-group v-model="form.status">
                                <el-radio v-for="dict in statusOptions" :key="dict.value" :label="dict.value">{{
                                    dict.label }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="备注">
                            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="open = false">取 消</el-button>
            </div>
        </el-dialog>



    </div>
</template>

<script>
export default {
    components: {},
    data() {
        return {
            queryParams: {},
            // 遮罩层
            loading: true,
            // 用户表格数据
            userList: null,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 勾选元素
            selection: [],
            // 表单参数
            form: {
                userId: undefined,
                deptId: undefined,
                roleIds: [],
                userName: undefined,
                nickName: undefined,
                password: undefined,
                phonenumber: undefined,
                email: undefined,
                sex: undefined,
                status: "0",
                remark: undefined,
            },
            userList: [],
            //分页条件
            page: {
                pageNum: 1,
                pageSize: 50,
                total: 0
            },
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 角色选项
            roleOptions: [],
            sexOptions: [
                { label: "男", value: "0" },
                { label: "女", value: "1" }
            ],
            statusOptions: [
                { label: "正常", value: "0" },
                { label: "停用", value: "1" }
            ],

            // 表单校验
            rules: {
                userName: [
                    { required: true, message: "用户名称不能为空", trigger: "blur" },
                    { min: 2, max: 20, message: '用户名称长度必须介于 2 和 20 之间', trigger: 'blur' }
                ],
                nickName: [
                    { required: true, message: "用户昵称不能为空", trigger: "blur" }
                ],
                password: [
                    { required: true, message: "用户密码不能为空", trigger: "blur" },
                    { min: 5, max: 20, message: '用户密码长度必须介于 5 和 20 之间', trigger: 'blur' }
                ],
                email: [
                    {
                        type: "email",
                        message: "请输入正确的邮箱地址",
                        trigger: ["blur", "change"]
                    }
                ],
                phonenumber: [
                    {
                        pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
                        message: "请输入正确的手机号码",
                        trigger: "blur"
                    }
                ]
            }
        }
    },
    computed: {},
    created() {
        this.getRoleList()
        this.getList();
    },
    mounted() { },
    methods: {
        /** 查询用户列表 */
        getList() {
            this.loading = true;
            this.$request({
                url: '/baseApi/system/user/pageList',
                method: 'get',
                params: {
                    ...this.queryParams, ...this.page
                }
            }).then((res) => {
                if (res.code === 200) {
                    this.loading = false;
                    this.userList = res.data;
                }
            })
        },
        getRoleList() {
            this.$request({
                url: '/baseApi/system/role/list',
                method: 'get',
                params: {

                }
            }).then((res) => {
                if (res.code === 200) {
                    this.roleOptions = res.data;
                }
            })
        },
        handleQuery() {
            this.page.current = 1;
            this.getList();
        },

        // 多选框选中数据
        handleSelectionChange(selection) {
            this.selection = selection;
            this.ids = selection.map(item => item.userId);
            this.single = selection.length != 1;
            this.multiple = !selection.length;
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.title = "添加用户";
            this.open = true
        },
        /** 修改按钮操作 */
        async handleUpdate(row) {
            this.form = this.selection[0] || row
            const roleIds = await this.getUserRoleList(row.userId)
            this.form.roleIds = roleIds.map(item => item.roleId)
            this.title = "修改用户";
            this.open = true
        },
        /** 获取用户角色集合 */
        getUserRoleList(userId) {
            return new Promise((resolve, reject) => {
                this.$request({
                    url: '/baseApi/system/user/getUserRoleList',
                    method: 'get',
                    params: {
                        userId: userId
                    }
                }).then((res) => {
                    resolve(res.data)
                })
            })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const userIds = row.userId || this.ids;
            this.$confirm('是否确认删除用户编号为"' + row.userName + '"的数据项？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$request.post('/baseApi/system/user/delete', null, {
                    params: {
                        userIds: userIds
                    },
                    paramsSerializer: {
                        indexes: null
                    }
                }).then(res => {
                    this.handleQuery();
                    this.$message({
                        message: '操作成功',
                        type: 'success'
                    });
                })

            }).catch(() => { })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    let url = ''
                    if (this.form.userId != undefined) {
                        url = '/baseApi/system/user/udpate'
                    } else {
                        url = '/baseApi/system/user/insert'
                    }
                    this.$request({
                        url: url,
                        method: 'post',
                        data: this.form
                    }).then((res) => {
                        if (res.code === 200) {
                            this.open = false;
                            this.$message({
                                message: '操作成功',
                                type: 'success'
                            });
                            this.handleQuery()
                        }
                    })
                }
            });
        },
        //改变页数据量
        handleSizeChange(val) {
            this.page.pageSize = val
            this.getList()
        },
        //改变当前页
        handleCurrentChange(val) {
            this.page.pageNum = val
            this.getList()
        },

        /** 重置密码按钮操作 */
        handleResetPwd(row) {
            this.$prompt('请输入"' + row.userName + '"的新密码', "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                closeOnClickModal: false,
                inputPattern: /^.{5,20}$/,
                inputErrorMessage: "用户密码长度必须介于 5 和 20 之间"
            }).then(({ value }) => {
                //修改密码
                this.$request({
                    url: '/baseApi/system/user/resetUserPwd',
                    method: 'get',
                    params: {
                        userId: row.userId,
                        password: value
                    }
                }).then((res) => {
                    if (res.code === 200) {
                        this.$message({
                            message: '操作成功',
                            type: 'success'
                        });
                    }
                })
            }).catch(() => { });
        },
        /** 分配角色操作 */
        handleAuthRole: function (row) {
            const userId = row.userId;
            this.$router.push("/system/user-auth/role/" + userId);
        },
        resetForm() {
            this.$data.form = this.$options.data().form
            this.$refs.form && this.$refs.form.resetFields()
        },

    },
}
</script>
<style lang="scss" scoped>
//@import url(); 引入公共css类样式
.el-dropdown {
    color: #409EFF;
    font-size: 12px;
}
</style>